package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    private final String KEY = "DishShowBycategoryId_";

    //根据分类id查询菜品
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result getBy_category_id(Integer categoryId){
        List<Dish> list = dishService.getBy_category_id(categoryId);
        return Result.success(list);
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> getBypage(DishPageQueryDTO dto){
        PageResult result = dishService.getBypage(dto);
        return Result.success(result);

    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售，停售")
    public Result start_or_stop(@PathVariable Integer status, Long id){
        dishService.start_or_stop(status,id);
        delete_cache(KEY);//全部清除；若要做到精准清除键值对，还得查询出该菜品的分类id，又是对数据库的操作，故这里采用全部清除，下同
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result getByid(@PathVariable Long id){
        DishVO result = dishService.getByid(id);
        return Result.success(result);
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result add(@RequestBody DishDTO dto){
        log.info("拿到了新增的菜品信息：{}",dto);
        dishService.add(dto);
        //清理缓存数据
        String key = KEY + dto.getCategoryId();
        delete_cache(key);//精准清除
        return Result.success();
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dto){
        dishService.update(dto);

        delete_cache(KEY);//全部清除
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("批量删除")
    public Result delete(String ids){
        dishService.delete(ids);
        delete_cache(KEY);//全部清除
        return Result.success();
    }

    private void delete_cache(String pattern_key){
        Set<String> keys_deleted = redisTemplate.keys(pattern_key+"*");
        redisTemplate.delete(keys_deleted);
    }//清楚redis中以pattern_key开头或者具有类似结构的键值对(全部清除，这是一种比较简单的方法，还可以在不同的方法去精准清除对应的键值对）

}
